package com.yuke.cloud.service.pmc.controller.frontend;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuke.cloud.common.core.support.BaseController;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.pmc.dto.ProdSpecGoodsInfoDto;
import com.yuke.cloud.service.api.wmc.dto.StorageSpecInfoDto;
import com.yuke.cloud.service.pmc.dto.*;
import com.yuke.cloud.service.pmc.entity.ProdSpec;
import com.yuke.cloud.service.pmc.service.ProdSpecService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
* Created by zys on 2018/09/30.
*/
@Slf4j
@Api(value = "WEB - ProdSpecController", tags = "处理ProdSpec相关请求", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
@RequestMapping("/mall/prod/spec")
public class MallProdSpecController extends BaseController {
    @Resource
    private ProdSpecService prodSpecService;
    @Resource
    private RedisTemplate redisTemplate;

    @PostMapping("/goods")
    @ApiOperation(httpMethod = "POST", value = "获取所有商品")
    public Wrapper<PageInfo<ProdSpec>>  getSpecGoods(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                     @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size,
                                                     @RequestBody(required = false) ProdSpecGoodsDto prodSpecGoodsDto){
        PageHelper.startPage(page, size);
        List<ProdSpecGoodsDto> prodSpecGoods = prodSpecService.getProdSpecGoods(prodSpecGoodsDto);
        PageInfo pageInfo = new PageInfo(prodSpecGoods);
        return  WrapMapper.ok(pageInfo);
    }
    @GetMapping("/app/recommend")
    @ApiOperation(httpMethod = "GET", value = "app首页商品推荐")
    public Wrapper<List<ProdSpecInfoAndPriceDto>> recommendList(@RequestParam("longitude") String longitude, @RequestParam("latitude") String latitude) {
        List<ProdSpecInfoAndPriceDto> prodSpecInfoAndPriceDtos = prodSpecService.getListRecommend(longitude, latitude);
        return WrapMapper.ok(prodSpecInfoAndPriceDtos);
    }

    @GetMapping("/app/introduce/{specId}")
    @ApiOperation(httpMethod = "GET", value = "商品规格介绍")
    public Wrapper<String> getIntroduce(@PathVariable Long specId) {
        ProdSpec prodSpec = prodSpecService.findById(specId);
        if (prodSpec!=null){
            String introduce = prodSpec.getIntroduce();
        }

        return WrapMapper.ok(prodSpecService.selectByKey(specId).getIntroduce());
    }

    @PostMapping("/app/condition")
    @ApiOperation(httpMethod = "POST", value = "app")
    public Wrapper<PageInfo<ProdSpecInfoAndPriceDto>> getAppSpecByCondition(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                                        @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size,
                                                                            @ApiParam(name = "shopId", value = "店铺ID") @RequestParam(required = false) Long shopId,
                                                                        @RequestBody(required = false) ProdSpecInfoAndPriceDto prodSpecInfoAndPriceDto) {


        PageHelper.startPage(page, size);
        List<ProdSpecInfoAndPriceDto> prodSpecs= prodSpecService.getAppSpecByCondition(prodSpecInfoAndPriceDto, shopId);

        PageInfo pageInfo = new PageInfo(prodSpecs);
        return WrapMapper.ok(pageInfo);
    }

    /**
     * 根据分类、搜索关键字获取商品品牌
     * saleType: 0：所有商品，1：仅针对零售类商品，2：仅针对批发类商品
     */
    @GetMapping("/getBrands")
    @ApiOperation(httpMethod = "GET", value = "app")
    public Wrapper<List<ProdBrandDto>> getBrands(@ApiParam(name = "saleType", value = "销售类型", defaultValue = "0") @RequestParam(defaultValue = "0") Byte saleType,
                                           @ApiParam(name = "categoryId", value = "商品分类ID") @RequestParam(required = false) Long categoryId,
                                           @ApiParam(name = "keyWord", value = "商品搜索关键字") @RequestParam(required = false) String keyWord) {
        List<ProdBrandDto> list = prodSpecService.getBrands(categoryId, saleType, keyWord);
        System.out.println("类="+categoryId);
        System.out.println("type = "+saleType);
        System.out.println("keyWord="+keyWord);
        System.out.println("商品品牌"+list);
        return WrapMapper.ok(list);

    }

    // 根据商品spec id获取该商品规格主属性及其值
    @GetMapping("/mainAttribute/{specId}")
    @ApiOperation(httpMethod = "GET", value = "根据productId及specId获取货品的主属性及其值")
    public Wrapper<List<ProdMainAttrDetailDto>> getMainAttribute(@ApiParam(name = "specId", value = "商品规格id") @PathVariable Long specId) {
        return WrapMapper.ok(prodSpecService.getMainAttribute(specId));
    }

    // 根据商品spec id获取商品的主属性及期所有规格的值
    @GetMapping("/mainAttributeList/{specId}")
    @ApiOperation(httpMethod = "GET", value = "根据productId获取商品所有的主属性及其值")
    public Wrapper<ProdMainAttrDto> getMainAttributeList(@ApiParam(name = "productId", value = "商品id") @PathVariable Long specId,
                                                         @ApiParam(name = "saleType", value = "销售类型") @RequestParam Byte saleType) {
        return WrapMapper.ok(prodSpecService.getMainAttributeList(specId, saleType));
    }

    // 根据商品的productId，主属性值组合获取商品相关信息
    @PostMapping("/getSpecByMainAttribute")
    @ApiOperation(httpMethod = "POST", value = "根据productId获取商品所有的主属性及其值")
    public Wrapper<ProdSpecInfoAndPriceDto> getSpecByMainAttribute(@ApiParam(name = "prodMainAttrDto", value = "请求参数") @RequestBody(required = false) ProdMainAttrDto prodMainAttrDto,
                                                                   @ApiParam(name = "saleType", value = "销售类型") @RequestParam Byte saleType,
                                                                   @ApiParam(name = "shopId", value = "店铺ID") @RequestParam(required = false) Long shopId) {
        return WrapMapper.ok(prodSpecService.getSpecByMainAttribute(prodMainAttrDto, saleType, shopId));
    }

    @PostMapping("/ifExist")
    @ApiOperation(httpMethod = "POST", value = "根据specName判断该商品是否存在")
    public Wrapper ifExist(@ApiParam(name = "id", value = "记录id") @RequestBody ProdSpec prodSpec) {

        Example example = new Example(ProdSpec.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("specName", prodSpec.getSpecName());

        if (prodSpec.getSpecId() != null) {
            criteria.andNotEqualTo("specId", prodSpec.getSpecId());
        }
        int count = prodSpecService.selectCountByExample(example);
        return WrapMapper.ok(count);
    }

    @GetMapping("/getSpecList")
    @ApiOperation(httpMethod = "GET", value = "获取所有记录:ID,图片，名字，货号，进货价")
    public Wrapper<List<ProdSpecGoodsInfoDto>> specList(@RequestParam(required = false) Long groupId) {
        List<ProdSpecGoodsInfoDto> list = prodSpecService.findSpecAll(groupId);
        return WrapMapper.ok(list);
    }

    //添加浏览商品记录到redis
    @PostMapping("/addProducRecording")
    public Wrapper<Boolean> addProducRecording(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        String specId = jsonObject.getString("specId");
        Boolean flag = prodSpecService.addProducRecording(userId, specId);

        return flag ? WrapMapper.ok(flag) : WrapMapper.error("商品之前已浏览");
    }

    @PostMapping("/getProducRecording")
    public Wrapper<List<StorageSpecInfoDto>> getProducRecording(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        String shopId = jsonObject.getString("shopId");
        List<StorageSpecInfoDto> list = prodSpecService.getRecordingByUserId(userId, shopId );

        return WrapMapper.ok(list);

    }
    @PostMapping("/getProducRecordingCount")
    public Wrapper getProducRecordingCount(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        String shopId = jsonObject.getString("shopId");
        String key = "User:" + userId + ":Recording";
        Set<Long> specIds = redisTemplate.opsForZSet().range(key, 0, -1);

        return WrapMapper.ok(specIds.size());

    }

    @DeleteMapping("/delProducRecording")
    public Wrapper delProducRecording(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        List<String> specId = (List<String>)jsonObject.get("specId");

        String key = "User:" + userId + ":Recording";
        for(String spec : specId){
            redisTemplate.opsForZSet().remove(key,spec);
        }
        return WrapMapper.ok();

    }
    @GetMapping("/getSpecInfoBySpecCode")
    @ApiOperation(httpMethod = "POST", value = "app")
    public Wrapper<PageInfo<ProdSpecGoodsInfoDto>> getSpecInfoBySpecCode(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                                            @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size,
                                                                            @ApiParam(name = "specCode", value = "条码ID") @RequestParam(defaultValue = "0") String specCode) {


        PageHelper.startPage(page, size);
        List<ProdSpecGoodsInfoDto> prodSpecs= prodSpecService.getSpecInfoBySpecCode(specCode);

        PageInfo pageInfo = new PageInfo(prodSpecs);
        return WrapMapper.ok(pageInfo);
    }
}
